package com.signature.auto.common.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.signature.auto.common.application.ApplicationInfo;
import com.signature.auto.common.consts.ApiSignConst;
import com.signature.auto.common.error.ApiErrorCode;
import com.signature.auto.common.exception.ApiSignException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

/**
 * @author Jerry
 * @date 2024-01-24 15:10
 */
public class ApiRequestForServlet implements ApiRequest {

    private static final String REQUEST_METHOD_POST = "POST";

    protected HttpServletRequest request;

    public ApiRequestForServlet(HttpServletRequest request) {
        this.request = request;
    }

    public Object getSource() {
        return this.request;
    }

    public String getParam(String name) {
        return this.request.getParameter(name);
    }

    public List<String> getParamNames() {
        Enumeration<String> parameterNames = this.request.getParameterNames();
        List<String> list = new ArrayList<>();

        while (parameterNames.hasMoreElements()) {
            list.add((String) parameterNames.nextElement());
        }

        return list;
    }

    public Map<String, Object> getParamMap() {

        // 判断是get请求还是post请求
        String method = getMethod();
        if (REQUEST_METHOD_POST.equals(method)) {
            Map<String, String[]> parameterMap = this.request.getParameterMap();
            JSONObject params;
            // 获取请求中的参数信息
            StringBuffer data = new StringBuffer();
            String line;
            BufferedReader reader;
            try {
                reader = request.getReader();
                while (null != (line = reader.readLine())) {
                    data.append(line);
                }
            } catch (IOException e) {
                throw new ApiSignException(e).setCode(ApiErrorCode.CODE_12004);
            }
            Map<String, Object> result = JSONUtil.toBean(data.toString(), Map.class);
            return result;

        } else {
            Map<String, String[]> parameterMap = this.request.getParameterMap();
            Map<String, Object> map = new LinkedHashMap<>(parameterMap.size());
            Iterator var3 = parameterMap.keySet().iterator();
            while (var3.hasNext()) {
                String key = (String) var3.next();
                String[] values = parameterMap.get(key);
                map.put(key, values[0]);
            }
            return map;
        }
    }

    @Override
    public Map<String, Object> getParamMap(Boolean checkHeaderIsNull) {
        if (checkHeaderIsNull) {
            String token = getHeader(ApiSignConst.HEADER);
            if (token == null) {
                throw new ApiSignException(ApiSignConst.HEADER + "不正确");
            }
        }
        Map<String, Object> paramMap = getParamMap();
        if (paramMap.isEmpty()) {
            throw new ApiSignException("参数异常");
        }
        return paramMap;
    }

    public String getHeader(String name) {
        return this.request.getHeader(name);
    }

    public String getCookieValue(String name) {
        Cookie[] cookies = this.request.getCookies();
        if (cookies != null) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for (int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                if (cookie != null && name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }

    public String getRequestPath() {
        return ApplicationInfo.cutPathPrefix(this.request.getRequestURI());
    }

    public String getUrl() {
        // TODO 未调用方提供昂基础路径信息
//        String currDomain = ApiSignContext.getConfig().getBaseUrl();
//        return !ApiFoxUtil.isEmpty(currDomain) ? currDomain + this.getRequestPath() : this.request.getRequestURL().toString();
        return null;

    }

    public String getMethod() {
        return this.request.getMethod();
    }


    @Override
    public Object forward(String path) {
        // todo
        return null;
    }


}
